/*
 * @Author: zhangzhen
 * @Date: 2023-01-05 15:41:30
 * @LastEditors: zhangzhen
 * @LastEditTime: 2023-02-28 16:24:57
 *
 */
import React, {useState, useContext, FC} from 'react';
import {Input, Modal, Button, Form, Popconfirm} from 'antd';
import {cloneDeep} from 'lodash';
import styles from './styles.module.scss';
import {FormContext} from '../../context';

const AddOption: FC<{value?: any; onChange?: (value: any) => void}> = ({
    value,
    onChange,
}) => {
    const {
        currentItem,
        setFormConTextValue,
        currentIndex,
        formConTextValue,
        setCurrentItem,
    } = useContext(FormContext);
    const [visible, setVisible] = useState(false);
    const [isEdit, setIsEdit] = useState<boolean>(false);
    const [optionIndex, setOptionIndex] = useState<number|null>();
    const [addForm] = Form.useForm();
    // 设置options
    const setOption = (
        index: number,
        isDelete: boolean,
        key?: 'label' | 'value',
        param?: any,
    ) => {
        if (onChange) {
            if (isDelete) {
                value.splice(index, 1);
            }
            if (key) {
                value[index][key] = param;
            }
            onChange([...value]);
        } else {
            const cloneValue = cloneDeep(formConTextValue);
            const cloneOptions = cloneValue[currentIndex].options;
            if (isDelete) {
                cloneOptions && cloneOptions.splice(index, 1);
            }
            if (cloneOptions && key) {
                cloneOptions[index][key] = param;
            }
            cloneValue[currentIndex].options = cloneOptions;
            setFormConTextValue(cloneValue);
            setCurrentItem(cloneValue[currentIndex]);
        }
    };

    // 新增options
    const addOption = () => {
        if (onChange) {
            addForm.validateFields().then((values) => {
                if (!value) {
                    value = [];
                }
                value.push(values);
                onChange([...value]);
            });
        } else {
            const cloneValue = cloneDeep(formConTextValue);
            const cloneOptions = cloneValue[currentIndex].options || [];
            addForm.validateFields().then((values) => {
                if(optionIndex===0||optionIndex){
                    cloneOptions.splice(optionIndex,1,{...values})
                }else{
                    cloneOptions?.push({...values});
                }
                cloneValue[currentIndex].options = cloneOptions;
                setFormConTextValue(cloneValue);
                setCurrentItem(cloneValue[currentIndex]);
            });
        }
        setVisible(false);
    };
    
    return (
        <div className={styles.addOptionBox}>
            <Button
                onClick={() => {
                    setVisible(true);
                    setOptionIndex(null)
                }}>
                新增一条
            </Button>
            {/* 设置options */}
            {currentItem.options &&
                currentItem.options.map((item, index) => (
                    <div
                        // eslint-disable-next-line react/no-array-index-key
                        key={index}
                        style={{
                            display: 'flex',
                            marginTop: '3px',
                            alignItems: 'center',
                            justifyContent: 'space-between',
                        }}>
                        <span title={item.label} className={styles.optionName}>
                            {item.label}
                        </span>

                        <Button
                            style={{marginLeft: '5px'}}
                            onClick={() => {
                                addForm.setFieldValue('label', item.label);
                                addForm.setFieldValue('value', item.value);
                                setOptionIndex(index);
                                setIsEdit(true);
                                setVisible(true);
                            }}>
                            编辑
                        </Button>

                        <Popconfirm
                            title="确认要删除吗？"
                            placement="left"
                            onConfirm={() => {
                                // 需要深拷贝
                                setOption(index, true);
                            }}
                            okText="是"
                            cancelText="否">
                            <Button style={{marginLeft: '5px'}}>删除</Button>
                        </Popconfirm>
                    </div>
                ))}
            {/* 设置columnsOptions */}
            {value &&
                value.map((item: any, index: number) => (
                    <div
                        key={item.value}
                        style={{
                            display: 'flex',
                            marginTop: '3px',
                            alignItems: 'center',
                        }}>
                        <span title={item.label} className={styles.optionName}>
                            {item.label}
                        </span>

                        <Popconfirm
                            title="确认要删除吗？"
                            placement="left"
                            onConfirm={() => {
                                // 需要深拷贝
                                setOption(index, true);
                            }}
                            okText="是"
                            cancelText="否">
                            <Button style={{marginLeft: '5px'}}>删除</Button>
                        </Popconfirm>
                    </div>
                ))}
            <Modal
                getContainer={false}
                open={visible}
                title={isEdit ? '编辑' : '新增'}
                destroyOnClose
                width={400}
                onCancel={() => {
                    setVisible(false);
                    setIsEdit(false);
                }}
                onOk={() => {
                    addForm.submit();
                }}>
                <Form form={addForm} preserve={false} onFinish={addOption}>
                    <Form.Item
                        label="名称"
                        name="label"
                        rules={[{required: true, message: '请输入'},{
                            validator(rule, value, callback) {
                                const cloneValue = cloneDeep(formConTextValue);
                                const cloneOptions = cloneValue[currentIndex].options 
                                if(cloneOptions.findIndex((item:any)=>item.label===value)>-1) {
                                    callback("存在重复名称请重新填写")
                                }
                            },
                        }]}>
                        <Input placeholder="请输入" maxLength={50} />
                    </Form.Item>
                    <Form.Item
                        label="字段"
                        name="value"
                        rules={[{required: true, message: '请输入'},{
                            validator(rule, value, callback) {
                                const cloneValue = cloneDeep(formConTextValue);
                                const cloneOptions = cloneValue[currentIndex].options 

                                if(cloneOptions.findIndex((item:any)=>item.value===value)>-1) {
                                    callback("存在重复字段请重新填写")
                                }
                            },
                        }]}>
                        <Input placeholder="请输入" maxLength={50} />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default AddOption;
